<template>
  <div class="Channel-Edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button
          class="edit-btn"
          type="danger"
          plain
          round
          size="mini"
          @click="isEdit=!isEdit"
          >{{isEdit?'完成':'编辑'}}
      </van-button>
    </van-cell>
    <!-- 我的频道内容 -->
    <van-grid class="my-grid" :gutter="10">
      <van-grid-item
      class="grid-item"
       v-for="(channel,index) in myChannels"
       :key="index"
       @click="onMyChannelClick(channel,index)"
       >
       <van-icon v-show="isEdit&&!fixedChannels.includes(channel.id)" slot="icon" name="clear"></van-icon>
       <!-- 对象中的key代表要作用的css类名 -->
       <span class="text"
        slot="text"
        :class="{active:index===active}"
        >
        {{channel.name}}
        </span>
      </van-grid-item>
    </van-grid>
    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">频道推荐</div>
    </van-cell>
    <!-- 频道推荐内容 -->
    <van-grid class="recommend-grid" :gutter="10">
      <van-grid-item
      class="grid-item"
       v-for="(channel,index) in recommendChannels"
       :key="index"
       icon="plus"
       :text="channel.name"
       @click="onAllChannel(channel)"
       />
    </van-grid>
  </div>
</template>

<script>
import { getAllChannels, addUserChannel, deleteUserChannel } from '@/api/channel'
import _ from 'lodash'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  components: {},
  props: {
    active: {
      type: Number,
      required: true // 是否必须
    },
    myChannels: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      allChannels: [], // 所以频道
      isEdit: false, // 控制编辑状态的显示
      fixedChannels: [0] // 固定频道,不允许删除
    }
  },
  computed: {
    ...mapState(['user']),
    recommendChannels () {
      // filter 把符合条件的元素返回到新数组
      // const r = this.allChannels.filter(channel => {
      //   // find 找到符合条件的第一个就返回，后面就不再查找！
      //   return !this.myChannels.find(myChannel => myChannel.id === channel.id)
      //   // 能不能改成下面写法？为什么？晚上想明白
      //   // return this.myChannels.find(myChannel => myChannel.id !== channel.id)
      // })
      const r2 = _.differenceBy(this.allChannels, this.myChannels, 'id')
      return r2
    }
  },
  watch: {},
  created () {
    this.loadAllChannels()
  },
  mounted () {},
  methods: {
    async loadAllChannels () {
      try {
        const { data } = await getAllChannels()
        this.allChannels = data.data.channels
      } catch {
        this.$toast('数据获取失败')
      }
    },
    // 添加频道
    async onAllChannel (channel) {
      this.myChannels.push(channel)
      // 数据持久化处理
      if (this.user) {
        // 一登录, 吧数据通过接口请求放到线上
        try {
          await addUserChannel({
            id: channel.id, // 频道id
            seq: this.myChannels.length // 序号
          })
        } catch (err) {
          this.$toast('保存失败,请稍后重试')
        }
      } else {
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    onMyChannelClick (channel, index) {
      if (this.isEdit) {
        // 编辑状态,删除频道
        if (this.fixedChannels.includes(channel.id)) {
          // 如果是固定频道不删除
          return
        }
        if (index <= this.active) {
          // 如果说你删除的是激活项前面的数据，会导致激活项的索引小 1
          // 但是你传递过来的 active 的数值是没有变化的（删不删并不会影响 active 的变化）
          // 所以如果你还想让 active 和索引对应上，只需要让 active 也减去1不就行了吗
          // 让激活频道的索引 - 1
          this.$emit('update-active', this.active - 1)
        }
        this.myChannels.splice(index, 1)

        // 数据持久化
        this.deleteUserChannel(channel)
      } else {
        // 非编辑状态,切换频道
        this.$emit('update-active', index, false)
      }
    },
    // 删除持久化频道
    async deleteUserChannel (channel) {
      try {
        if (this.user) {
          // 已登录,将数据更新到后端
          await deleteUserChannel(channel.id)
        } else {
          // 未登录,将数据更新到本地
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (err) {
        this.$toast('操作失败,请稍后重试')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.Channel-Edit {
  padding: 85px 0;
  .title-text {
    font-size: 32px;
    font-weight: 700;
    color: #333333;
  }
  // 编辑按钮
  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }
   /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }
  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
  /deep/ .recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }
}
</style>
